﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ITProject.Repository.Abstract;
using ITProject.Domain;
using ITProject.Domain.Entities;
using ITProject.WebUI.Models;
using ITProject.WebUI.Models.ProjectTeamLeader;

namespace ITProject.WebUI.Controllers
{
    public partial class ProjectTeamLeaderController : Controller
    {
        public ProjectTeamLeaderController(IProjectRepository projectRepo, IUserRepository userRepo)
        {
            projectRepository = projectRepo;
            userRepository = userRepo;
        }

        private IProjectRepository projectRepository;
        private IUserRepository userRepository;
        
        private bool CheckAccess(string projectName)
        {
            if (projectRepository.GetProjectUserRole(projectName, HttpContext.User.Identity.Name) == UserRole.NoRole || 
                projectRepository.GetProjectUserRole(projectName, HttpContext.User.Identity.Name)==UserRole.User)
                return false;
            return true;
        }
        
        [Authorize]
        public virtual ViewResult Index(string projectName)
        {
            if (!CheckAccess(projectName))
                throw new Exception("Brak dostępu");
            int userId=userRepository.GetUserByLogin(User.Identity.Name).Id;
            int projectId = projectRepository.GetProjectByName(projectName).Id;
            Team[] teamManageByUser = projectRepository.GetTeamsManageByUser(projectId,userId);
            ProjectTeamLeaderIndexViewModel[] vmTab = ProjectTeamLeaderIndexViewModel.Convert(teamManageByUser);
            ViewData["ProjectName"] = projectName;
            ViewData["Role"] = projectRepository.GetProjectUserRole(projectName, HttpContext.User.Identity.Name);
            return View(vmTab);
        }

        [Authorize]
        public virtual ViewResult AddTeamTask(string projectName, int teamId)
        {
            if (!CheckAccess(projectName))
                throw new Exception("Brak dostępu");
            Project project=projectRepository.GetProjectByName(projectName);
            User user = userRepository.GetUserByLogin(User.Identity.Name);
            Team team = projectRepository.GetTeamById(teamId);
            if (team.LeaderId != user.Id)
                throw new Exception("Brak dostępu");
            Feature[] teamFeatures=projectRepository.GetTeamFeatures(teamId, project.Id);
            List<string> teamUserList=projectRepository.GetTeamUsers(teamId);
            teamUserList.Add(user.Login);
            string[] teamUsers = teamUserList.ToArray();
            ProjectTeamLeaderAddTeamTaskViewModel vm = new ProjectTeamLeaderAddTeamTaskViewModel();
            vm.FeatureList = new List<SelectListItem>();
            for (int i = 0; i < teamFeatures.Length; i++)
            {
                SelectListItem item = new SelectListItem { Text = teamFeatures[i].Name };
                vm.FeatureList.Add(item);
            }
            vm.UserList = new List<SelectListItem>();
            for (int i = 0; i < teamUsers.Length; i++)
            {
                SelectListItem item = new SelectListItem { Text = teamUsers[i] };
                vm.UserList.Add(item);
            }
            vm.PlannedEndDate = DateTime.Now.AddDays(7);
            vm.ProjectName = projectName;
            ViewData["Role"] = projectRepository.GetProjectUserRole(projectName, HttpContext.User.Identity.Name);
            return View(vm);
        }

        [Authorize]
        [HttpPost]
        public virtual ActionResult AddTeamTask(ProjectTeamLeaderAddTeamTaskViewModel vm)
        {
            string projectName = vm.ProjectName;
            int teamId = vm.TeamId;
            if (!CheckAccess(projectName))
                throw new Exception("Brak dostępu");
            Project project = projectRepository.GetProjectByName(projectName);
            User user = userRepository.GetUserByLogin(User.Identity.Name);
            Team team = projectRepository.GetTeamById(teamId);
            if (team.LeaderId != user.Id)
                throw new Exception("Brak dostępu");
            // walidacja nazwy zadania
            Task[] tasks = projectRepository.GetProjectTasks(project.Id);
            for (int i = 0; i < tasks.Length; i++)
                if (vm.Name == tasks[i].Name)
                {
                    ModelState.AddModelError("Name", "Już isnieje w projekcie zadanie o podanej nazwie");
                    // uzupełnienie odpowiednich list
                    Feature[] features = projectRepository.GetTeamFeatures(team.Id, project.Id);
                    string[] users=projectRepository.GetTeamUsers(team.Id).ToArray();

                    vm.FeatureList = new List<SelectListItem>(features.Length);
                    for (int j = 0; j < features.Length; j++)
                        vm.FeatureList.Add(new SelectListItem { Text = features[j].Name });
                    vm.UserList = new List<SelectListItem>(users.Length);
                    for (int j = 0; j < users.Length; j++)
                        vm.UserList.Add(new SelectListItem { Text = users[j] });
                    ViewData["Role"] = projectRepository.GetProjectUserRole(projectName, HttpContext.User.Identity.Name);
                    return View(vm);
                }
            int featureId = projectRepository.GetFeatureByName(vm.ReturnFeature, project.Id).Id;
            User taskUser = userRepository.GetUserByLogin(vm.ReturnUser);
            Task task = ProjectTeamLeaderAddTeamTaskViewModel.Convert(vm, project.Id, taskUser.Id, featureId);
            int creatorId = user.Id;
            projectRepository.AddNewTask(task, creatorId);
            return RedirectToAction(MVC.ProjectTeamLeader.ActionNames.Index, new { projectName = projectName });
        }

    }
}

